package com.chapter.sample.jvm.gc;

import java.lang.ref.WeakReference;

public class WeakReferenceTest {
    public static class User {
        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int id;
        public String name;

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        //构造弱引用对象
        WeakReference<User> userWeakReference = new WeakReference<>(new User(1, "sunwukong"));

        //从弱引用中重写获取对象
        System.out.println(userWeakReference.get());

        //
        System.gc();

        //不管当前内存空间是否足够,都会进行回收
        System.out.println("After GC");
        //重写尝试从弱引用中重写获取对象
        System.out.println(userWeakReference.get());
    }
}
